{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "dd4ed7c1-700d-4985-8d01-91889b76ddef",
   "metadata": {},
   "source": [
    "# [GoNB](https://github.com/janpfeifer/gonb) WASM (WebAssembly) Examples "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d5a6e431-18aa-4dd7-9dad-ead67a58f69c",
   "metadata": {},
   "source": [
    "### Flag Parsing in Wasm\n",
    "\n",
    "**GoNB** exports arguments passed in a slice for Wasm programs in the global variable `GonbWasmArgs`.\n",
    "\n",
    "This allows for parsing into flags where desired:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2a953aef-a046-41a9-8191-b36cfd871a7e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\t- Added replace rule for module \"github.com/janpfeifer/gonb\" to local directory \"/home/janpf/Projects/gonb\".\n"
     ]
    }
   ],
   "source": [
    "!*rm -f go.work && go work init\n",
    "!*go work use . \"${HOME}/Projects/gonb\"\n",
    "%goworkfix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "bda2da44-fcce-438c-8bcf-f5c324f04d41",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<div id=\"log_id_gonb_id_c2d3e63b\"></div>\n",
       "<form id=\"form_id_gonb_id_c2d3e63b\">\n",
       "    <input type=\"submit\" value=\"Send\" />\n",
       "    <input type=\"text\" id=\"msg_id_gonb_id_c2d3e63b\" size=\"64\" autofocus />\n",
       "</form>\n"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "text/javascript": [
       "(()  => {\n",
       "    var conn;\n",
       "    var msg = document.getElementById(\"msg_id_gonb_id_c2d3e63b\");\n",
       "    var log = document.getElementById(\"log_id_gonb_id_c2d3e63b\");\n",
       "    var form = document.getElementById(\"form_id_gonb_id_c2d3e63b\");\n",
       "\n",
       "    function appendLog(item) {\n",
       "        var doScroll = log.scrollTop > log.scrollHeight - log.clientHeight - 1;\n",
       "        log.appendChild(item);\n",
       "        if (doScroll) {\n",
       "            log.scrollTop = log.scrollHeight - log.clientHeight;\n",
       "        }\n",
       "    }\n",
       "\n",
       "    form.onsubmit = function () {\n",
       "        if (!conn) {\n",
       "            return false;\n",
       "        }\n",
       "        if (!msg.value) {\n",
       "            return false;\n",
       "        }\n",
       "        conn.send(msg.value);\n",
       "        msg.value = \"\";\n",
       "        return false;\n",
       "    };\n",
       "\n",
       "    if (window[\"WebSocket\"]) {\n",
       "        conn = new WebSocket(\"ws://\" + document.location.host + \"/api/kernels/99cf1321-773b-4f75-8efb-67a7b804a688/channels\");\n",
       "        conn.onclose = function (evt) {\n",
       "            var item = document.createElement(\"div\");\n",
       "            item.innerHTML = \"<b>Connection closed.</b>\";\n",
       "            appendLog(item);\n",
       "        };\n",
       "        conn.onmessage = function (evt) {\n",
       "            const data = JSON.parse(evt.data);\n",
       "            console.log(JSON.stringify(data, null, 2));\n",
       "            // var messages = evt.data.split('\\n');\n",
       "            // for (var i = 0; i < messages.length; i++) {\n",
       "            //     var item = document.createElement(\"div\");\n",
       "            //     item.innerText = messages[i];\n",
       "            //     appendLog(item);\n",
       "            // }\n",
       "        };\n",
       "    } else {\n",
       "        var item = document.createElement(\"div\");\n",
       "        item.innerHTML = \"<b>Your browser does not support WebSockets.</b>\";\n",
       "        appendLog(item);\n",
       "    }\n",
       "})();"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import (\n",
    "        \"github.com/janpfeifer/gonb/gonbui\"\n",
    ")\n",
    "%%\n",
    "gonbui.ConnectToJupyterServer()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "664846b0-bf5b-480a-9113-2ba48124fc90",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BASH_EXECUTION_STRING='set | grep GONB'\n",
      "GONB_DIR=/home/janpf/Projects/gonb/examples\n",
      "GONB_JUPYTER_ROOT=/home/janpf\n",
      "GONB_JUPYTER_SESSION_ID=99cf1321-773b-4f75-8efb-67a7b804a688\n",
      "GONB_PIPE=/tmp/gonb_pipe_743942013\n",
      "GONB_TMP_DIR=/tmp/gonb_ce4b7d59\n"
     ]
    }
   ],
   "source": [
    "!set | grep GONB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "dfee138f-1af9-4ca2-b8fb-74cda9b1fb3f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div id=\"gonb_id_2c1b09ff\"></div><script src=\"/files/jupyter_files/e514a190/wasm_exec.js\"></script>"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "text/javascript": [
       "\n",
       "(() => {\n",
       "\tvar go_e514a190 = new globalThis.Go();\n",
       "\tgo_e514a190.argv = [\"js\"].concat([\"--name=World\", ]);\n",
       "\tconsole.log(\"argv=\"+go_e514a190.argv);\n",
       "\tWebAssembly.instantiateStreaming(fetch(\"/files/jupyter_files/e514a190/gonb_cell.wasm\"), go_e514a190.importObject).\n",
       "\t\tthen((result) => { go_e514a190.run(result.instance); });\n",
       "})();\n"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%wasm\n",
    "import (\n",
    "    \"flag\"\n",
    "    \"fmt\"\n",
    "    \"os\"\n",
    "    \n",
    "    \"github.com/janpfeifer/gonb/gonbui/wasm\"\n",
    ")\n",
    "\n",
    "var flagName = flag.String(\"name\", \"\", \"enter your name\")\n",
    "\n",
    "%% --name=World\n",
    "fmt.Printf(\"os.Args=%v\\n\", os.Args)\n",
    "flag.Parse()\n",
    "fmt.Printf(\"--name=%s\\n\", *flagName)\n",
    "// wasm.ParseFlags(GonbWasmArgs)  // Parse flags form the args passed in GonbWasmArgs.\n",
    "wasm.Alertf(\"Hello %s!\", *flagName)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a4d26900-1ce4-401a-a887-6a8f99776d78",
   "metadata": {},
   "source": [
    "### Simplest Widget: Sum Two Numbers\n",
    "\n",
    "An example of making interactive widgets using Go and WASM inside GoNB.\n",
    "\n",
    "First we define a function that sum numbers given in strings. \n",
    "Notice we run it normally, not yet in Wasm."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "599cd63c-dc05-4a8c-b8fb-43ba8d9ac8b6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 + 2 = 3\n"
     ]
    }
   ],
   "source": [
    "func SumStr(aStr, bStr string) string {\n",
    "    a, err := strconv.Atoi(aStr)\n",
    "    if err != nil {\n",
    "        return \"#invalid\"\n",
    "    }\n",
    "    b, err := strconv.Atoi(bStr)\n",
    "    if err != nil {\n",
    "        return \"#invalid\"\n",
    "    }\n",
    "    x := a+b\n",
    "    if x != 42 {\n",
    "        return strconv.Itoa(x)\n",
    "    } else {\n",
    "        return \"life, the universe and everything ...\"\n",
    "    }\n",
    "}\n",
    "\n",
    "%%\n",
    "fmt.Println(\"1 + 2 =\", SumStr(\"1\", \"2\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2bc6abc5-ff04-4555-887e-7aa91de49683",
   "metadata": {},
   "source": [
    "Now, we define the Wasm program that creates the input fields and listen to its changes, updating the sum:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "8aa7b544-2b63-4da9-a7aa-08f36c9244a9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<script src=\"/files/jupyter_files/22be0bfe/wasm_exec.js\"></script>\n",
       "<script>\n",
       "var go_22be0bfe = new Go();\n",
       " \n",
       "WebAssembly.instantiateStreaming(fetch(\"/files/jupyter_files/22be0bfe/gonb_cell.wasm\"), go_22be0bfe.importObject).\n",
       "\tthen((result) => { go_22be0bfe.run(result.instance); });\n",
       "</script>\n",
       "<div id=\"gonb_id_6ad96910\"></div>\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%wasm\n",
    "import (\n",
    "    \"github.com/janpfeifer/gonb/gonbui/wasm\"\n",
    "    \"syscall/js\"\n",
    ")\n",
    "\n",
    "%%\n",
    "// mainDiv := document.Call(\"getElementById\", GONB_WASM_DIV_ID)\n",
    "// mainDiv.Set(\"innerHTML\", \"<b>Hello World!</b>\")\n",
    "div := wasm.ById(GonbWasmDivId)\n",
    "inputA := wasm.AsInput(wasm.NewElem(\"input\", \"width=10\"))\n",
    "inputB := wasm.AsInput(wasm.NewElem(\"input\", \"width=10\"))\n",
    "result := wasm.AsInput(wasm.NewElem(\"input\", \"width=10\", \"readonly\"))\n",
    "\n",
    "wasm.Append(div, inputA)\n",
    "wasm.AppendHTML(div, \" + \")\n",
    "wasm.Append(div, inputB)\n",
    "wasm.AppendHTML(div, \" + \")\n",
    "wasm.Append(div, result)\n",
    "\n",
    "// Sum numbers whenever they change.\n",
    "updater := func(_ wasm.EventCompatible) {\n",
    "    result.SetValue(SumStr(inputA.Value(), inputB.Value()))\n",
    "}\n",
    "wasm.On(inputA, \"keyup\", updater)\n",
    "wasm.On(inputB, \"keyup\", updater)\n",
    "\n",
    "// Never return, otherwise the Go wasm program stops working and won't update the result.\n",
    "wasm.WaitForever()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Go (gonb)",
   "language": "go",
   "name": "gonb"
  },
  "language_info": {
   "codemirror_mode": "",
   "file_extension": ".go",
   "mimetype": "",
   "name": "go",
   "nbconvert_exporter": "",
   "pygments_lexer": "",
   "version": "go1.21.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
